from django.db import models
from django.db.models import permalink
from django.contrib.auth.models import User
from django.contrib.markup.templatetags.markup import textile, markdown, restructuredtext
from django.utils.safestring import mark_safe
from tagging.fields import TagField
from tagging.models import Tag
from nx.blog.managers import PostManager

def process_markup(text, markup):
    if markup == 'textile':
        return textile(text)
    elif markup == 'markdown':
        return markdown(text)
    elif markup == 'rst':
        return restructuredtext(text)
    else:
        return mark_safe(text)

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique_for_date='published')
    body = models.TextField()
    more = models.TextField(blank=True)
    tease = models.TextField(blank=True)
    author = models.ForeignKey(User, blank=True, null=True, related_name='blog_posts')
    allow_comments = models.BooleanField(default=True)

    MARKUP_CHOICES = (
        ('html', 'HTML'),
        ('markdown', 'Markdown'),
        ('textile', 'Textile'),
        ('rst', 'Restructured Text')
    )
    markup = models.CharField(max_length=50, choices=MARKUP_CHOICES, default='textile')

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('public', 'Public'),
    )
    status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='public')

    published = models.DateTimeField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    
    tags = TagField()

    objects = PostManager()

    class Meta:
        ordering = ('-published',)
        get_latest_by = 'published'

    def __unicode__(self):
        return self.title

    @permalink
    def get_absolute_url(self):
        return ('nx.blog.views.post_detail', None, {
            'year': self.published.year,
            'month': self.published.strftime('%b').lower(),
            'day': self.published.day,
            'slug': self.slug
        })
    
    def get_tags(self):
        return Tag.objects.get_for_object(self)

    def get_previous_post(self):
        return self.get_previous_by_published(status='public')
    
    def get_next_post(self):
        return self.get_next_by_published(status='public')
        
    def body_safe(self):
        return process_markup(self.body, self.markup)
        
    def more_safe(self):
        return process_markup(self.more, self.markup)
